<?php

	// +----------------------------------------------------------------------
	// | 邮件
	// +----------------------------------------------------------------------
	// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
	// +----------------------------------------------------------------------
	// | Author: 微尘 <yicmf@qq.com>
	// +----------------------------------------------------------------------

	namespace app\event\ucenter;

	use app\model\ucenter\Email as EmailModel;
	use app\model\ucenter\EmailHistory as EmailHistoryModel;
	use app\model\ucenter\EmailTemplate as EmailTemplateModel;
	use app\common\event\Base;
	use think\Exception;
	use think\facade\Config;
	use think\facade\Event;
	use think\facade\Log;
	use think\facade\Session;
	use app\model\ucenter\User as UserModel;

	class Email extends Base
	{

		/**
		 * 发送邮件
		 * @param array $param
		 * @param null|UserModel $user
		 * @return mixed
		 * @author  : 微尘 <yicmf@qq.com>
		 */
		public static function send($param, $user = null)
		{
			try {
				if (empty($param['email']) && !is_null($user)) {
					$param['email'] = $user['email'];
				}
				$email = EmailModel::where('address', $param['email'])->find();
				if (!$email) {
					// 新增
					$insert['address'] =  $param['email'];
					$insert['invite_code'] =  empty($param['invite_code'])?'':$param['invite_code'];
					$email = EmailModel::create($insert);
				}
				if (isset($param['email_template_id'])) {
					$template = EmailTemplateModel::where('id', $param['email_template_id'])->find();
				} else {
					$template = EmailTemplateModel::where('name', 'in', [$param['type'], 'base'])->order('level DESC')->find();
				}
				// 发送历史
				$history = [];
				$history['email_template_id'] = $template['id'];
				$history['email_id'] = $email['id'];
				$history['address'] = $email['address'];
				$history['token'] = md5(uniqid());
				if ('bind' == $param['type']) {
					// 绑定邮箱，需要确认当前邮箱无人使用
					$param['activate_url'] = $user['nickname'];
					$param['nickname'] = $user['nickname'];
					$param['subject'] = '绑定邮箱';
					$param['body'] = '您在绑定邮箱操作，请输入验证码【' . $param['code'] . '】进行操作！';
				} elseif ('code' == $param['type']) {
					// 注册，需要确认当前邮箱无人使用
					$param['subject'] = '安全验证';
					$param['body'] = '本次安全验证码【' . $param['code'] . '】';
				} elseif ('register' == $param['type']) {
					// 注册，需要确认当前邮箱无人使用
					// 注册，需要确认当前邮箱无人使用
					$param['subject'] = '验证账号';
					$param['activate'] = $history['token'];
					$url = (string)url('/ucenter/register/activate',['t'=>$param['activate']],true,true);
					$param['body'] = '您好：

请点击下面的链接来激活您的账号。

'.$url.'
如果您的邮箱不支持链接点击，请将以上链接地址拷贝到你的浏览器地址栏中。

该验证邮件有效期为12小时，超时请重新发送邮件。

';
//					$param['subject'] = '注册账号';
//					$param['body'] = '您在注册账号，请输入验证码【' . $param['code'] . '】进行操作！';
				}elseif ('register2' == $param['type']) {
					// 注册，需要确认当前邮箱无人使用
					$param['subject'] = '验证账号';
					$param['activate'] = $history['token'];
					$url = (string)url('/ucenter/register/activate',['t'=>$param['activate']],true,true);
					$param['body'] = '您好：

请点击下面的链接来激活您的账号。

'.$url.'
如果您的邮箱不支持链接点击，请将以上链接地址拷贝到你的浏览器地址栏中。

该验证邮件有效期为12小时，超时请重新发送邮件。

';
				} elseif ('auth' == $param['type']) {
					// 注册，需要确认当前邮箱无人使用
					$param['subject'] = '实名认证';
					$param['activate'] = $history['token'];
					$url = (string)url('/ucenter/register/activate',['t'=>$param['activate']],true,true);
					$param['body'] = '您好：

您正在进行实名认证，认证为：'.$param['idcard_name'].'，当前验证码是：

'.$param['code'].'
 
当前验证码有效期为10分钟，超时请重新发送邮件。

';
				} elseif ('password_reset' == $param['type']) {
					// 重置登录密码
					$param['subject'] = '重置登录密码';
					$param['activate'] = $history['token'];
					$url = (string)url('/ucenter/register/reset',['t'=>$param['activate'],'type'=>'login'],true,true);
					$param['body'] = '您好：

请点击下面的链接来重置登录密码。

'.$url.'
如果您的邮箱不支持链接点击，请将以上链接地址拷贝到你的浏览器地址栏中。

该验证邮件有效期为12小时，超时请重新发送邮件。

';
				} elseif ('email_reset' == $param['type']) {
					// 重置登录邮箱
					$param['subject'] = '重置登录邮箱';
					$param['activate'] = $history['token'];
					$url = (string)url('/ucenter/register/reset_email',['t'=>$param['activate']],true,true);
					$param['body'] = '您好：

请点击下面的链接来重置登录邮箱。

'.$url.'
如果您的邮箱不支持链接点击，请将以上链接地址拷贝到你的浏览器地址栏中。

该验证邮件有效期为12小时，超时请重新发送邮件。

';
				} elseif ('pay_password_reset' == $param['type']) {
					// 重置登录密码
					$param['subject'] = '重置支付密码';
					$param['activate'] = $history['token'];
					$url = (string)url('/ucenter/register/reset',['t'=>$param['activate'],'type'=>'pay'],true,true);
					$param['body'] = '您好：

请点击下面的链接来重置登录密码。

'.$url.'
如果您的邮箱不支持链接点击，请将以上链接地址拷贝到你的浏览器地址栏中。

该验证邮件有效期为12小时，超时请重新发送邮件。

';
				} elseif ('forget' == $param['type']) {
					// 忘记密码，需要确认当前手机已经注册
					$param['subject'] = '忘记密码';
					$param['body'] = '您在找回密码，请输入验证码【' . $param['code'] . '】进行操作！';
				} elseif ('cash' == $param['type']) {
					//                    $param['nickname'] = $user['nickname'];
				}  elseif ('stock_alarm' == $param['type']) {
					$good = $user->goods()->where('id', $param['good_id'])->find();
					if (!$good) {
						throw new Exception('商品不存在');
					}
					$param['subject'] = '商品库存预警';
					$param['body'] = '您的商品【' . $good['title'] . '】库存剩余【' . $good['stock'] . '】，预警值【' . $good['stock_alarm'] . '】，请及时处理库存。';
				} elseif ('safe_code' == $param['type']) {
					$param['subject'] = '安全操作码';
					$param['body'] = '您当前安全操作码是【' . $param['code'] . '】，如果非您本人请忽略！';
				} else {
					$param['subject'] = $param['title'];
					$param['body'] = $param['content'];
				}
				$param['time'] = time_format();
				$param['docs'] = 1;
				$param['domain'] = 1;
				$param['logo'] = 'http://fe.ksyun.com/project/resource/img/logo.png';
				$param['wechat'] = 'http://fe.ksyun.com/project/resource/img/wechat.png';
				$param['web_site_title'] = Config::get('setting.web_site_title');
				if (!is_null($user)) {
					$param['nickname'] = $user['nickname'];
				}
				$history['param'] = $param;
				$history = EmailHistoryModel::create($history);
				$param['unsubscribe'] = url('ucenter/Email/unsubscribe', ['token' => $history['token']], true, true);
				$view = app('view');
				$body = $view->display($template['body'], $param);
				$subject = $view->display($template['subject'], $param);
				$history['subject'] = $subject;
				$history['content'] = $param['body'];
				$history['body'] = $body;
				if (1 == $email['is_subscribe']) {
					$data = Event::trigger('send_email', $history, true);
					$history['result'] = $data['code'];
					if ($data['code'] === 0) {
						$history['send_time'] = time_format();
					}
					$history['result_message'] = $data['message'];
					$history['channel'] = isset($data['channel']) ? $data['channel'] : '';
				} else {
					$history['result'] = 1;
					$history['result_message'] = '用户取消订阅';
					$data['code'] = 0;
					$data['message'] = '用户取消订阅';
				}
				$history->save();
			} catch (Exception $e) {
				$data['code'] = 1;
				$data['message'] = $e->getMessage();
				$data['file'] = $e->getFile();
				$data['line'] = $e->getLine();
			}
			return $data;
		}

	}
